package com.ukefu.webim.util;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.ui.ModelMap;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.ai.DicSegment;
import com.ukefu.util.es.SearchTools;
import com.ukefu.util.task.export.ExcelExporterQualityResultProcess;
import com.ukefu.webim.service.es.VoiceTranscriptionRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.repository.AgentServiceRepository;
import com.ukefu.webim.service.repository.CallCenterSkillRepository;
import com.ukefu.webim.service.repository.CallOutRoleRepository;
import com.ukefu.webim.service.repository.JobDetailRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.QualityFormFilterItemRepository;
import com.ukefu.webim.service.repository.QualityFormFilterRepository;
import com.ukefu.webim.service.repository.QualityMissionHisRepository;
import com.ukefu.webim.service.repository.QualityResultItemRepository;
import com.ukefu.webim.service.repository.QualityResultRecordRepository;
import com.ukefu.webim.service.repository.QualityResultRepository;
import com.ukefu.webim.service.repository.QualityTemplateItemRepository;
import com.ukefu.webim.service.repository.QualityTemplateRepository;
import com.ukefu.webim.service.repository.StatusEventRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.service.repository.UserRoleRepository;
import com.ukefu.webim.web.model.AgentService;
import com.ukefu.webim.web.model.CallCenterSkill;
import com.ukefu.webim.web.model.JobDetail;
import com.ukefu.webim.web.model.MetadataTable;
import com.ukefu.webim.web.model.QualityFormFilter;
import com.ukefu.webim.web.model.QualityFormFilterItem;
import com.ukefu.webim.web.model.QualityMissionHis;
import com.ukefu.webim.web.model.QualityResult;
import com.ukefu.webim.web.model.QualityResultExporter;
import com.ukefu.webim.web.model.QualityResultItem;
import com.ukefu.webim.web.model.QualityResultRecord;
import com.ukefu.webim.web.model.QualityTemplate;
import com.ukefu.webim.web.model.QualityTemplateItem;
import com.ukefu.webim.web.model.StatusEvent;
import com.ukefu.webim.web.model.TableProperties;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.VoiceTranscription;
import com.ukefu.webim.web.model.WorkOrders;

/**
 * 	质检 -	公共 工具类
 *
 */
public class QualityDataUtils {
	
	/**
	 * 我的部门以及授权给我的部门 - 筛选表单
	 * @param filterRes
	 * @param userRoleRes
	 * @param callOutRoleRes
	 * @param user
	 * @return
	 */
	public static List<QualityFormFilter> getFormFilterList(QualityFormFilterRepository filterRes,UserRoleRepository userRoleRes , CallOutRoleRepository callOutRoleRes, final User user){
		
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		
		List<QualityFormFilter> formFilterList = filterRes.findAll(new Specification<QualityFormFilter>(){
			@Override
			public Predicate toPredicate(Root<QualityFormFilter> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				
				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));
				
				if(organList.size() > 0){
					
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(in) ;
				
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}});
		
		return formFilterList;
	}
	
	/**
	 * 	质检数据 - 回收到池子
	 * @param dataid
	 * @param type
	 * @param orgi
	 */
	public static void Recycle(String dataid, String type, String orgi, String recyctype) {
		
		StatusEventRepository statusEventRes = UKDataContext.getContext().getBean(StatusEventRepository.class);
		WorkOrdersRepository workOrdersRes = UKDataContext.getContext().getBean(WorkOrdersRepository.class);
		AgentServiceRepository agentServiceRes = UKDataContext.getContext().getBean(AgentServiceRepository.class);
		QualityMissionHisRepository qcMissionRes = UKDataContext.getContext().getBean(QualityMissionHisRepository.class);
		QualityResultRepository qcResultRes = UKDataContext.getContext().getBean(QualityResultRepository.class);
		QualityResultItemRepository qcResultItemRes = UKDataContext.getContext().getBean(QualityResultItemRepository.class);
		QualityResultRecordRepository qualityResultRecordRes = UKDataContext.getContext().getBean(QualityResultRecordRepository.class);	
		String data = null;
		if(type.equals(UKDataContext.QcFormFilterTypeEnum.CALLEVENT.toString())) {
			StatusEvent statusEvent = statusEventRes.findById(dataid);
			if(statusEvent != null) {
				statusEvent.setQualitydistime(null);
				statusEvent.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					statusEvent.setQualitydisorgan(null);
					statusEvent.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					statusEvent.setQualityactid(null);
					statusEvent.setQualityfilterid(null);
					statusEvent.setAssuser(null);
					statusEvent.setQualitytype(null);
					
				}else {
					statusEvent.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
				}
				statusEvent.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				statusEvent.setQualityorgan(null);
				statusEvent.setQualityscore(0);
				statusEvent.setQualitytime(null);
				statusEvent.setQualityuser(null);
				statusEvent.setAutoquality(false);
				statusEvent.setSpotqc(false);
				statusEvent.setSpotqctime(null);
				statusEvent.setSpotqcsuccess(false);
				statusEvent.setAppealqc(false);
				statusEvent.setArbitrateqc(false);
				statusEvent.setQualitypass(0);
				statusEvent.setQcaplsubmitime(null);
				statusEvent.setQcarbsubmitime(null);
				statusEventRes.save(statusEvent);
				data = statusEvent.getId();
			}
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.WORKORDERS.toString())) {
			WorkOrders workOrders = workOrdersRes.getByIdAndOrgi(dataid, orgi);
			if(workOrders != null) {
				workOrders.setQualitydistime(null);
				workOrders.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					workOrders.setQualitydisorgan(null);
					workOrders.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					workOrders.setQualityactid(null);
					workOrders.setQualityfilterid(null);
					workOrders.setAssuser(null);
				}else {
					workOrders.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
					workOrders.setQualitytype(null);
				}
				workOrders.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				workOrders.setQualityorgan(null);
				workOrders.setQualityscore(0);
				workOrders.setQualitytime(null);
				workOrders.setQualityuser(null);
				workOrders.setQcaplsubmitime(null);
				workOrders.setQcarbsubmitime(null);
				workOrdersRes.save(workOrders);
				data = workOrders.getId();
			}
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.AGENTSERVICE.toString())) {
			AgentService agentService = agentServiceRes.findByIdAndOrgi(dataid, orgi);
			if(agentService != null) {
				agentService.setQualitydistime(null);
				agentService.setQualitydisuser(null);
				if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
					//回收到公共池子
					agentService.setQualitydisorgan(null);
					agentService.setQualitydistype(UKDataContext.QualityDisStatusType.NOT.toString());
					agentService.setQualityactid(null);
					agentService.setQualityfilterid(null);
					agentService.setAssuser(null);
					
					agentService.setQualitytype(null);
				}else {
					agentService.setQualitydistype(UKDataContext.QualityDisStatusType.DISORGAN.toString());
				}
				agentService.setQualitystatus(UKDataContext.QualityStatus.NO.toString());
				agentService.setQualityorgan(null);
				agentService.setQualityscore(0);
				agentService.setQualitytime(null);
				agentService.setQualityuser(null);
				agentService.setQcaplsubmitime(null);
				agentService.setQcarbsubmitime(null);
				agentServiceRes.save(agentService);
				data = agentService.getId();
			}
		}
		if(data != null) {
			List<QualityMissionHis> missionList = qcMissionRes.findByDataidAndOrgi(data, orgi);
			if(missionList.size() > 0) {
				/*QualityActivityTask task = qcTaskRes.findByIdAndOrgi(missionList.get(0).getTaskid(), orgi);
				if(task != null) {
					if(recyctype.equals(UKDataContext.RecycleType.PUBLIC.toString())) {
						task.setRenum(task.getRenum() + 1);//回收到池子数
					}else {
						task.setReorgannum(task.getReorgannum() + 1);//回收到部门数
						task.setNotassigned(task.getNotassigned() + 1);//未分配数
					}
					qcTaskRes.save(task);
				}*/
				qcMissionRes.delete(missionList);
			}
			List<QualityResult> qualityresultList = qcResultRes.findByDataidAndOrgi(data, orgi) ;
			if (qualityresultList != null && qualityresultList.size() > 0) {
				for(QualityResult qualityresult : qualityresultList){
					List<QualityResultItem> qualityResultItemList = qcResultItemRes.findByResultidAndOrgi(qualityresult.getId(), orgi) ;
					if (qualityResultItemList!=null && qualityResultItemList.size()>0) {
						qcResultItemRes.delete(qualityResultItemList);
					}
				}
				qcResultRes.delete(qualityresultList);
			}
			List<QualityResultRecord> recordList= qualityResultRecordRes.findByDataidAndOrgi(dataid, orgi);
			if (recordList!= null && recordList.size() > 0) {
				qualityResultRecordRes.delete(recordList);
			}
			
		}
	}
	/**
	 * 搜索条件
	 */
	public static void searchCondition(ModelMap map ,HttpServletRequest request,final User user) {
		
		JobDetailRepository qcActivityRes = UKDataContext.getContext().getBean(JobDetailRepository.class);
		OrganRepository organRes = UKDataContext.getContext().getBean(OrganRepository.class);
		QualityFormFilterRepository qcFormFilterRes = UKDataContext.getContext().getBean(QualityFormFilterRepository.class);
		
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		map.addAttribute("organList", organRes.findAll(organList));
		map.put("activityList", qcActivityRes.findAll(new Specification<JobDetail>(){
			@Override
			public Predicate toPredicate(Root<JobDetail> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				list.add(cb.equal(root.get("tasktype").as(String.class), UKDataContext.TaskType.QUALITY.toString()));

				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));

				if(organList.size() > 0){
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}	
				list.add(in) ;
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}}));
		map.put("formFilterList", qcFormFilterRes.findAll(new Specification<QualityFormFilter>(){
			@Override
			public Predicate toPredicate(Root<QualityFormFilter> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				In<Object> in = cb.in(root.get("organ"));
				
				list.add(cb.equal(root.get("orgi").as(String.class), user.getOrgi()));
				
				if(organList.size() > 0){
					
					for(String id : organList){
						in.value(id) ;
					}
				}else{
					in.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(in) ;
				
				Predicate[] p = new Predicate[list.size()];  
				return cb.and(list.toArray(p));   
			}}));
		map.put("allUserList",UKDataContext.getContext().getBean(UserRepository.class).findByOrgiAndDatastatus(user.getOrgi(), false));
	}
	
	public static BoolQueryBuilder searchWorkordersCon(ModelMap map ,HttpServletRequest request) {
		BoolQueryBuilder bool = new BoolQueryBuilder();
		//搜索框
		if(!StringUtils.isBlank(request.getParameter("q"))) {
			String q = request.getParameter("q") ;
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			if(!StringUtils.isBlank(q)){
				bool.must(QueryBuilders.boolQuery().must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND))) ;
				map.put("q", q) ;
			}
		}
		if(!StringUtils.isBlank(request.getParameter("qualityfilterid"))) {
			bool.must(termQuery("qualityfilterid", request.getParameter("qualityfilterid"))) ;
			map.put("qualityfilterid", request.getParameter("qualityfilterid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisuser"))) {
			bool.must(termQuery("qualitydisuser", request.getParameter("qualitydisuser"))) ;
			map.put("qualitydisuser", request.getParameter("qualitydisuser")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualityactid"))) {
			bool.must(termQuery("qualityactid", request.getParameter("qualityactid"))) ;
			map.put("qualityactid", request.getParameter("qualityactid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydistype"))) {
			bool.must(termQuery("qualitydistype", request.getParameter("qualitydistype"))) ;
			map.put("qualitydistype", request.getParameter("qualitydistype")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisorgan"))) {
			bool.must(termQuery("qualitydisorgan", request.getParameter("qualitydisorgan"))) ;
			map.put("qualitydisorgan", request.getParameter("qualitydisorgan")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitystatus"))) {
			bool.must(termQuery("qualitystatus", request.getParameter("qualitystatus"))) ;
			map.put("qualitystatus", request.getParameter("qualitystatus")) ;
		}
		RangeQueryBuilder rangeQuery = null ;
		if(!StringUtils.isBlank(request.getParameter("begin")) || !StringUtils.isBlank(request.getParameter("end"))){
			if(!StringUtils.isBlank(request.getParameter("begin"))) {
				try {
					rangeQuery = QueryBuilders.rangeQuery("qualitydistime").from(UKTools.dateFormate.parse(request.getParameter("begin")).getTime()) ;
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(!StringUtils.isBlank(request.getParameter("end")) ) {
				try {
					if(rangeQuery == null) {
						rangeQuery = QueryBuilders.rangeQuery("qualitydistime").to(UKTools.dateFormate.parse(request.getParameter("end")).getTime()) ;
					}else {
						rangeQuery.to(UKTools.dateFormate.parse(request.getParameter("end")).getTime()) ;
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			map.put("begin", request.getParameter("begin")) ;
			map.put("end", request.getParameter("end")) ;
		}
		if(rangeQuery != null) {
			bool.must(rangeQuery);
		}
		return bool;
	}
	
	public static int getNameNum(ModelMap map, String type, JobDetail act, User user) {
		
		QualityFormFilterItemRepository qcFormFilterRes = UKDataContext.getContext().getBean(QualityFormFilterItemRepository.class);		
		List<QualityFormFilterItem> qcFormFilterItemList = qcFormFilterRes.findByOrgiAndQcformfilterid(act.getOrgi(), act.getFilterid());
		int allsum = 0;
		if(type.equals(UKDataContext.QcFormFilterTypeEnum.CALLEVENT.toString())) {
			List<StatusEvent> callList = SearchTools.searchQualityStatusEvent(act.getOrgi(), qcFormFilterItemList, user);
			allsum = callList.size();
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.WORKORDERS.toString())) {
			List<WorkOrders> workList = SearchTools.searchQualityWorkOrders(act.getOrgi(), qcFormFilterItemList, user);
			allsum = workList.size();
		}else if(type.equals(UKDataContext.QcFormFilterTypeEnum.AGENTSERVICE.toString())) {
			List<AgentService> agentList = SearchTools.searchQualityAgentService(act.getOrgi(), qcFormFilterItemList, user);
			allsum = agentList.size();
		}
		map.addAttribute("allsum", allsum);
		return allsum;
	}
	
	public static List<StatusEvent> getOrganDisnotCallevent(User user){
		final String orgi = user.getOrgi();
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		StatusEventRepository statusEventRes = UKDataContext.getContext().getBean(StatusEventRepository.class);
		List<StatusEvent> list = statusEventRes.findAll(new Specification<StatusEvent>(){
			@Override
			public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("record").as(boolean.class), true)) ;
				//未分配
				list.add(cb.equal(root.get("qualitydistype").as(String.class), UKDataContext.QualityDisStatusType.DISORGAN.toString())) ;
				//权限控制
				In<Object> inOrgan = cb.in(root.get("qualitydisorgan"));
				if(organList.size() > 0){
					for(String id : organList){
						inOrgan.value(id) ;
					}
				}else{
					inOrgan.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(inOrgan) ;
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));  
			}}) ;
		return list;
	}
	public static List<WorkOrders> getOrganDisnotWorkorders(User user){
		List<String> organList = CallCenterUtils.getExistOrgan(user);
		WorkOrdersRepository workOrdersRes = UKDataContext.getContext().getBean(WorkOrdersRepository.class);
		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
		boolQueryBuilder.must(QueryBuilders.termQuery("qualitydistype" , UKDataContext.QualityDisStatusType.DISORGAN.toString()));
		//权限控制
		BoolQueryBuilder bool = new BoolQueryBuilder();
		if(organList.size() > 0) {
			for(String id : organList) {
				bool.should(QueryBuilders.termQuery("qualitydisorgan" , id));
			}
		}else {
			bool.should(QueryBuilders.termQuery("qualitydisorgan" , UKDataContext.UKEFU_SYSTEM_NO_DAT));
		}
		if(bool != null) {
			boolQueryBuilder.must(bool);
		}
		List<WorkOrders> list = workOrdersRes.findByOrgiAndQualitydisorgan(boolQueryBuilder);
		return list;
	}
	public static List<AgentService> getOrganDisnotAgent(User user){
		final String orgi = user.getOrgi();
		final List<String> organList = CallCenterUtils.getExistOrgan(user);
		AgentServiceRepository agentServiceRes = UKDataContext.getContext().getBean(AgentServiceRepository.class);
		List<AgentService> list = agentServiceRes.findAll(new Specification<AgentService>(){
			@Override
			public Predicate toPredicate(Root<AgentService> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();  
				list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
				list.add(cb.equal(root.get("qualitydistype").as(String.class), UKDataContext.QualityDisStatusType.DISORGAN.toString())) ;
				//权限控制
				In<Object> inOrgan = cb.in(root.get("qualitydisorgan"));
				if(organList.size() > 0){
					for(String id : organList){
						inOrgan.value(id) ;
					}
				}else{
					inOrgan.value(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
				}
				list.add(inOrgan) ;
				
				Predicate[] p = new Predicate[list.size()];  
			    return cb.and(list.toArray(p));   
			}
		}) ;
		return list;
	}
	
	public static void autoQualityStatusEvent(StatusEvent statusEvent) throws IOException {
		System.out.println("自动质检");
		if (statusEvent != null && !StringUtils.isBlank(statusEvent.getId())) {
			statusEvent.setAutoquality(true);
			QualityMissionHisRepository qualityMissionHisRes = UKDataContext.getContext().getBean(QualityMissionHisRepository.class);		
			QualityTemplateRepository qualityTemplateRes = UKDataContext.getContext().getBean(QualityTemplateRepository.class);		
			QualityTemplateItemRepository qualityTemplateItemRes = UKDataContext.getContext().getBean(QualityTemplateItemRepository.class);		
			QualityResultItemRepository qualityResultItemRes = UKDataContext.getContext().getBean(QualityResultItemRepository.class);		
			QualityResultRepository qualityResultRes = UKDataContext.getContext().getBean(QualityResultRepository.class);		
			VoiceTranscriptionRepository voiceTranscriptionRes = UKDataContext.getContext().getBean(VoiceTranscriptionRepository.class);
			QualityResultRecordRepository qualityResultRecordRes = UKDataContext.getContext().getBean(QualityResultRecordRepository.class);		
			if (!StringUtils.isBlank(statusEvent.getQualityactid()) && !StringUtils.isBlank(statusEvent.getTemplateid())) {
				QualityTemplate qualitytemplate = qualityTemplateRes.findByIdAndOrgi(statusEvent.getTemplateid(), UKDataContext.SYSTEM_ORGI) ; 
				int totalscore = 0;
				boolean isPass = false;
				StringBuilder content = new StringBuilder();//全部
				StringBuilder agentcontent = new StringBuilder();//坐席
				StringBuilder usercontent = new StringBuilder();//客户
				//获取质检内容
				List<VoiceTranscription> voiceTranscriptionList = voiceTranscriptionRes.findByCallidAndOrgi(statusEvent.getId(), UKDataContext.SYSTEM_ORGI);
				if (voiceTranscriptionList != null && voiceTranscriptionList.size() > 0) {
					for(VoiceTranscription voiceTranscription : voiceTranscriptionList) {
						if (!StringUtils.isBlank(voiceTranscription.getOnebest())) {
							content.append(voiceTranscription.getOnebest());
							if (!StringUtils.isBlank(voiceTranscription.getSpeaker()) && voiceTranscription.getSpeaker().equals("1")) {
								agentcontent.append(voiceTranscription.getOnebest());
							}
							if (!StringUtils.isBlank(voiceTranscription.getSpeaker()) && voiceTranscription.getSpeaker().equals("0")) {
								usercontent.append(voiceTranscription.getOnebest());
							}
						}
					}
				}
				QualityMissionHis qualityMissionHis = null;
				List<QualityMissionHis> qualityMissionHisList = qualityMissionHisRes.findByDataidAndOrgi(statusEvent.getId(), UKDataContext.SYSTEM_ORGI) ;
				if (qualityMissionHisList!=null && qualityMissionHisList.size()>0) {
					qualityMissionHis = qualityMissionHisList.get(0);
				}
				if (qualitytemplate != null && qualityMissionHis != null) {
					if (!StringUtils.isBlank(content.toString())) {
						boolean taboo = false;
						List<QualityTemplateItem> qualityTemplateItemList = qualityTemplateItemRes.findByTemplateidAndOrgi(statusEvent.getTemplateid(), UKDataContext.SYSTEM_ORGI) ;
						List<QualityResultItem> qualityResultItemList = new ArrayList<QualityResultItem>() ;
						QualityResult qcresult = new QualityResult() ;
						
						/**
						 * 检验禁忌项
						 */
						if (qualityTemplateItemList!=null && qualityTemplateItemList.size()>0) {
							for(QualityTemplateItem tItem : qualityTemplateItemList){
								if (tItem.getType().equals(UKDataContext.QcTemplateItemType.TABOO.toString())) {
									QualityResultItem ritem = new QualityResultItem();
									if (!StringUtils.isBlank(tItem.getWordstype())) {
										String text = null;
										if (!StringUtils.isBlank(tItem.getCtarget()) && tItem.getCtarget().equals("agent")) {
											text = agentcontent.toString();
										}else if (!StringUtils.isBlank(tItem.getCtarget()) && tItem.getCtarget().equals("user")) {
											text = usercontent.toString();
										}else{
											text = content.toString();
										}
										if (!StringUtils.isBlank(text)) {
											String[] tabooresults = DicSegment.parsebyLibkeys("taboo"+tItem.getWordstype(), text);
											if (tabooresults != null && tabooresults.length >0) {
												ritem.setNchit(Arrays.asList(tabooresults).toString());
												ritem.setScore(1);
												taboo = true;
											}
										}
									}
									ritem.setCreater(statusEvent.getQualitydisuser());
									ritem.setCreatetime(new Date());
									ritem.setName(tItem.getName());
									ritem.setOrgi(UKDataContext.SYSTEM_ORGI);
									ritem.setScheme(tItem.getScheme());
									ritem.setType(tItem.getType());
									ritem.setItemid(tItem.getId());
									ritem.setParentid(tItem.getParentid());
									ritem.setResultid(qcresult.getId());
									qualityResultItemList.add(ritem) ;
								}
							}
						}
						
						/**
						 * 检验质检项
						 */
						if (qualityTemplateItemList!=null && qualityTemplateItemList.size()>0) {
							for(QualityTemplateItem tItem : qualityTemplateItemList){
								if (!tItem.getType().equals(UKDataContext.QcTemplateItemType.TABOO.toString()) && tItem.getParentid().equals("0")) {//1级
									//
									QualityResultItem ritem = new QualityResultItem();
									int fenshu1 = 0;
									for(QualityTemplateItem tItem2 : qualityTemplateItemList){
										if (!tItem2.getParentid().equals("0") && tItem2.getParentid().equals(tItem.getId())) {//2级
											QualityResultItem ritem2 = new QualityResultItem();
											boolean hasp = false;
											int fenshu2 = 0;
											for(QualityTemplateItem tItem3 : qualityTemplateItemList){
												if (!tItem3.getParentid().equals("0") && tItem3.getParentid().equals(tItem2.getId())) {//3级
													hasp = true;
													QualityResultItem ritem3 = new QualityResultItem();
													if (!taboo) {
														String text = null;
														if (!StringUtils.isBlank(tItem3.getCtarget()) && tItem3.getCtarget().equals("agent")) {
															text = agentcontent.toString();
														}else if (!StringUtils.isBlank(tItem3.getCtarget()) && tItem3.getCtarget().equals("user")) {
															text = usercontent.toString();
														}else{
															text = content.toString();
														}
														if (!StringUtils.isBlank(text)) {
															if (!StringUtils.isBlank(tItem3.getNcontain())) {
																//'不可包含' 验证评分
																nContain(tItem3,ritem3,text,fenshu2);
															}
															if (!StringUtils.isBlank(tItem3.getMcontain()) && ritem3.getScore()==0) {
																//'必须包含' 验证评分
																mContain(tItem3,ritem3,text,fenshu2);
															}
														}
													}
													if (ritem3.getScore()==0) {
														ritem3.setScore(tItem3.getMinscore());
													}
													fenshu2 += ritem3.getScore();
													ritem3.setCreater(statusEvent.getQualitydisuser());
													ritem3.setCreatetime(new Date());
													ritem3.setMaxscore(tItem3.getMaxscore());
													ritem3.setMinscore(tItem3.getMinscore());
													ritem3.setName(tItem3.getName());
													ritem3.setOrgi(UKDataContext.SYSTEM_ORGI);
													ritem3.setScheme(tItem3.getScheme());
													ritem3.setType(tItem3.getType());
													ritem3.setItemid(tItem3.getId());
													ritem3.setParentid(tItem3.getParentid());
													ritem3.setResultid(qcresult.getId());
													ritem3.setCtarget(tItem3.getCtarget());
													qualityResultItemList.add(ritem3) ;
												}
											}
											ritem2.setScore(fenshu2);
											
											if (!hasp) {
												if (!taboo) {
													String text = null;
													if (!StringUtils.isBlank(tItem2.getCtarget()) && tItem2.getCtarget().equals("agent")) {
														text = agentcontent.toString();
													}else if (!StringUtils.isBlank(tItem2.getCtarget()) && tItem2.getCtarget().equals("user")) {
														text = usercontent.toString();
													}else{
														text = content.toString();
													}
													if (!StringUtils.isBlank(text)) {
														if (!StringUtils.isBlank(tItem2.getNcontain())) {
															//'不可包含' 验证评分
															nContain(tItem2,ritem2,text,fenshu1);
														}
														if (!StringUtils.isBlank(tItem2.getMcontain()) && ritem2.getScore()==0) {
															//'必须包含' 验证评分
															mContain(tItem2,ritem2,text,fenshu1);
														}
													}
												}
												if (ritem2.getScore()==0) {
													ritem2.setScore(tItem2.getMinscore());
												}
											}
											fenshu1 += ritem2.getScore();
											
											ritem2.setCreater(statusEvent.getQualitydisuser());
											ritem2.setCreatetime(new Date());
											ritem2.setMaxscore(tItem2.getMaxscore());
											ritem2.setMinscore(tItem2.getMinscore());
											ritem2.setName(tItem2.getName());
											ritem2.setOrgi(UKDataContext.SYSTEM_ORGI);
											ritem2.setScheme(tItem2.getScheme());
											ritem2.setType(tItem2.getType());
											ritem2.setItemid(tItem2.getId());
											ritem2.setParentid(tItem2.getParentid());
											ritem2.setResultid(qcresult.getId());
											ritem2.setCtarget(tItem2.getCtarget());
											qualityResultItemList.add(ritem2) ;
										}
									}
									///
									totalscore += fenshu1 ;
									ritem.setScore(fenshu1);
									ritem.setCreater(statusEvent.getQualitydisuser());
									ritem.setCreatetime(new Date());
									ritem.setMaxscore(tItem.getMaxscore());
									ritem.setMinscore(tItem.getMinscore());
									ritem.setName(tItem.getName());
									ritem.setOrgi(UKDataContext.SYSTEM_ORGI);
									ritem.setScheme(tItem.getScheme());
									ritem.setType(tItem.getType());
									ritem.setItemid(tItem.getId());
									ritem.setParentid(tItem.getParentid());
									ritem.setResultid(qcresult.getId());
									qualityResultItemList.add(ritem) ;
								}
							}
						}
						
						/**
						 * 得出质检结果
						 */
						if (taboo) {
							totalscore = 0;
						}else {
							if (UKDataContext.QcTemplateItemType.MINUS.toString().equals(qualitytemplate.getArithmetic())) {
								totalscore = qualitytemplate.getTotalscore()-totalscore ;
							}
						}
						if (qualitytemplate.getPassscore()<=totalscore) {
							isPass = true ;
						}
						qcresult.setCreater(statusEvent.getQualitydisuser());
						qcresult.setCreatetime(new Date());
						qcresult.setArithmetic(qualitytemplate.getArithmetic());
//								qcresult.setAdcom(qcFormFilterRequest.getAdcom());
//								qcresult.setImcom(qcFormFilterRequest.getImcom());
//								qcresult.setQacom(qcFormFilterRequest.getQacom());
//								qcresult.setRemarks(qcFormFilterRequest.getRemarks()) ;
						qcresult.setDataid(statusEvent.getId());
						qcresult.setOrgi(UKDataContext.SYSTEM_ORGI);
						qcresult.setTotalscore(qualitytemplate.getTotalscore());
						qcresult.setPassscore(qualitytemplate.getPassscore());
						qcresult.setScore(totalscore);
						qcresult.setQualityuser(statusEvent.getQualitydisuser());
						qcresult.setStatus(UKDataContext.QualityStatus.DONE.toString());
						qcresult.setQualitytype(qualitytemplate.getType());
						qcresult.setIsadcom(qualitytemplate.isIsadcom());
						qcresult.setIsimcom(qualitytemplate.isIsimcom());
						qcresult.setIsitemdir(qualitytemplate.isIsitemdir());
						qcresult.setIsitemrmk(qualitytemplate.isIsitemrmk());
						qcresult.setIsqacom(qualitytemplate.isIsqacom());
						qcresult.setIsrmk(qualitytemplate.isIsrmk());
						qcresult.setIsvp(qualitytemplate.isIsvp());
						qualityResultRes.save(qcresult) ;
						
						if (qualityResultItemList != null && qualityResultItemList.size() > 0) {
							qualityResultItemRes.save(qualityResultItemList) ;
						}
						if (qcresult != null) {
							QualityResultRecord qualityresultrecord = new QualityResultRecord();
							UKTools.copyProperties(qcresult, qualityresultrecord,"id");
							qualityresultrecord.setAutoquality(true);
							qualityresultrecord.setStatus(UKDataContext.QualityResultRecordStatus.NORMAL.toString());
							qualityresultrecord.setChecktype(UKDataContext.QualityCheckType.FIRST.toString());
							qualityresultrecord.setQualityresultitem(UKTools.toJson(qualityResultItemList));
							qualityResultRecordRes.save(qualityresultrecord);
						}
						qualityMissionHis.setQualityscore(totalscore);
						qualityMissionHis.setQualitypass(isPass? 1 : 0);
						qualityMissionHis.setQualitystatus(UKDataContext.QualityStatus.DONE.toString());
						statusEvent.setQualityscore(totalscore);
						statusEvent.setQualitystatus(UKDataContext.QualityStatus.DONE.toString());
						statusEvent.setQualitypass(isPass? 1 : 0);
					}else {
						qualityMissionHis.setQualitystatus(UKDataContext.QualityStatus.DISABLE.toString());
						statusEvent.setQualitystatus( UKDataContext.QualityStatus.DISABLE.toString());
					}
					statusEvent.setQualitytime(new Date());
					statusEvent.setQualityorgan(statusEvent.getQualitydisorgan());
					statusEvent.setQualityuser(statusEvent.getQualitydisuser());
					qualityMissionHis.setQualitytime(new Date());
					qualityMissionHis.setQualitytype(qualitytemplate.getType());
					qualityMissionHis.setQualityuser(statusEvent.getQualitydisuser());
					qualityMissionHis.setQualityorgan(statusEvent.getQualitydisorgan());
					qualityMissionHisRes.save(qualityMissionHis) ;
				}
			}
		}
	}
	
	public static void mContain(QualityTemplateItem tItem,QualityResultItem ritem,String content,int fenshu) {
		String mcontain = tItem.getMcontain();
		String tempstr = null;
		List<String> tempList = new ArrayList<String>();
		while (!StringUtils.isBlank(mcontain) && mcontain.contains("(")) {
			tempstr = null;
			tempstr = mcontain.substring(mcontain.indexOf("(", 0), mcontain.indexOf(")", 0)+1);
			if (!StringUtils.isBlank(tempstr)) {
				tempList.add(tempstr.replaceAll("[()]", ""));
			}
			mcontain = mcontain.replace(tempstr, "#");
		}
		String[] mcontains = mcontain.split("[, ，:；;\\n\t\\r ]");
		if (mcontains != null && mcontains.length > 0) {//判断外层
			for(String mword : mcontains) {
				if (content.contains(mword)) {
					ritem.setMchit(mword);
					ritem.setScore(tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMinscore():tItem.getMaxscore());
					fenshu += tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMinscore():tItem.getMaxscore();
					break;
				}
			}
		}
		if (tempList != null && tempList.size() > 0 && ritem.getScore()==0) {//判断内层
			boolean got = true;
			for(String tstr : tempList){
				got = true;
				String[] tstrarr = tstr.split(",");
				if (tstrarr != null && tstrarr.length > 0) {
					for(String ts : tstrarr) {
						if (!content.toString().contains(ts)) {
							got = false;
							break;
						}
					}
				}
				if (got) {
					ritem.setMchit(tstr);
					ritem.setScore(tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMinscore():tItem.getMaxscore());
					fenshu += tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMinscore():tItem.getMaxscore();
					break;
				}
			}
		}
	}
	
	public static void nContain(QualityTemplateItem tItem,QualityResultItem ritem,String content,int fenshu) {
		String ncontain = tItem.getNcontain();
		String tempstr = null;
		List<String> tempList = new ArrayList<String>();
		while (!StringUtils.isBlank(ncontain) && ncontain.contains("(")) {
			tempstr = null;
			tempstr = ncontain.substring(ncontain.indexOf("(", 0), ncontain.indexOf(")", 0)+1);
			if (!StringUtils.isBlank(tempstr)) {
				tempList.add(tempstr.replaceAll("[()]", ""));
			}
			ncontain = ncontain.replace(tempstr, "#");
		}
		String[] ncontains = ncontain.split("[, ，:；;\\n\t\\r ]");
		if (ncontains != null && ncontains.length > 0) {//判断外层
			for(String nword : ncontains) {
				if (content.contains(nword)) {
					ritem.setNchit(nword);
					ritem.setScore(tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMaxscore():tItem.getMinscore());
					fenshu += tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMaxscore():tItem.getMinscore();
					break;
				}
			}
		}
		if (tempList != null && tempList.size() > 0 && ritem.getScore()==0) {//判断内层
			boolean got = true;
			for(String tstr : tempList){
				got = true;
				String[] tstrarr = tstr.split(",");
				if (tstrarr != null && tstrarr.length > 0) {
					for(String ts : tstrarr) {
						if (!content.toString().contains(ts)) {
							got = false;
							break;
						}
					}
				}
				if (got) {
					ritem.setNchit(tstr);
					ritem.setScore(tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMaxscore():tItem.getMinscore());
					fenshu += tItem.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?tItem.getMaxscore():tItem.getMinscore();
					break;
				}
			}
		}
	}
	
	public static List<Predicate> getSearchStatusEvent(Root<?> root ,CriteriaBuilder cb ,ModelMap map , final HttpServletRequest request,String orgi ){
		UserRepository userRes = UKDataContext.getContext().getBean(UserRepository.class) ;
		OrganRepository organRes = UKDataContext.getContext().getBean(OrganRepository.class) ;
		CallCenterSkillRepository callCenterSkillRepository = UKDataContext.getContext().getBean(CallCenterSkillRepository.class);
		map.put("allUserList",userRes.findByOrgi(orgi));
		map.put("skillList",organRes.findByOrgi(orgi));
		List<CallCenterSkill> callCenterSkillList = callCenterSkillRepository.findByOrgi(orgi);
		map.addAttribute("callCenterSkillList", callCenterSkillList) ;
		
		List<Predicate> list = new ArrayList<Predicate>();
		//搜索条件
		if(!StringUtils.isBlank(request.getParameter("userid"))){
			list.add(cb.equal(root.get("userid").as(String.class), request.getParameter("userid"))) ;
			map.put("userid", request.getParameter("userid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("q"))) {
			String q = request.getParameter("q") ;
			q = q.replaceAll("(OR|AND|NOT|:|\\(|\\))", "") ;
			if(!StringUtils.isBlank(q)){
				Predicate p1 = cb.or(cb.like(root.get("discaller").as(String.class), "%"+request.getParameter("q")+"%")
						,cb.like(root.get("discalled").as(String.class), "%"+request.getParameter("q")+"%")
						);
				map.put("q", q) ;
				list.add(cb.and(p1));
			}
		}
		if(!StringUtils.isBlank(request.getParameter("qualityfilterid"))) {
			list.add(  cb.equal(root.get("qualityfilterid").as(String.class), request.getParameter("qualityfilterid"))) ;
			map.put("qualityfilterid", request.getParameter("qualityfilterid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisuser"))) {
			list.add( cb.equal(root.get("qualitydisuser").as(String.class), request.getParameter("qualitydisuser"))) ;
			map.put("qualitydisuser", request.getParameter("qualitydisuser")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualityactid"))) {
			list.add( cb.equal(root.get("qualityactid").as(String.class), request.getParameter("qualityactid")) );
			map.put("qualityactid", request.getParameter("qualityactid")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydistype"))) {
			list.add( cb.equal(root.get("qualitydistype").as(String.class), request.getParameter("qualitydistype"))) ;
			map.put("qualitydistype", request.getParameter("qualitydistype")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitydisorgan"))) {
			list.add( cb.equal(root.get("qualitydisorgan").as(String.class), request.getParameter("qualitydisorgan")) );
			map.put("qualitydisorgan", request.getParameter("qualitydisorgan")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualitystatus"))) {
			if (request.getParameter("qualitystatus").equals("no")) {
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.DONE.toString()) );
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.APPEAL.toString()) );
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.ARCHIVE.toString()) );
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.ARBITRATE.toString()) );
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.RECHECK.toString()) );
				list.add( cb.notEqual(root.get("qualitystatus").as(String.class), UKDataContext.QualityStatus.DISABLE.toString()) );
			}else{
				list.add( cb.equal(root.get("qualitystatus").as(String.class), request.getParameter("qualitystatus")) );
			}
			map.put("qualitystatus", request.getParameter("qualitystatus")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("autoquality"))) {
			boolean auto = ((request.getParameter("autoquality")).equals("1")|| request.getParameter("autoquality").equals("true"))?true:false;
			list.add( cb.equal(root.get("autoquality").as(boolean.class), auto)) ;
			map.put("autoquality", request.getParameter("autoquality")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("discaller"))){
			
			list.add(cb.or(cb.equal(root.get("discaller").as(String.class), request.getParameter("discaller")),
					cb.and(cb.equal(root.get("hidetype").as(String.class), UKDataContext.CallTypeEnum.IN.toString()),cb.equal(root.get("priphone").as(String.class), request.getParameter("discaller"))))) ;
			
			map.put("discaller", request.getParameter("discaller")) ;
		}
		list.add(cb.equal(root.get("orgi").as(String.class), orgi)) ;
		if(!StringUtils.isBlank(request.getParameter("discalled"))){
			
			list.add(cb.or(cb.equal(root.get("discalled").as(String.class), request.getParameter("discalled")),
					cb.and(cb.equal(root.get("hidetype").as(String.class), UKDataContext.CallTypeEnum.OUT.toString()),cb.equal(root.get("priphone").as(String.class), request.getParameter("discalled"))))) ;
			
			map.put("discalled", request.getParameter("discalled")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("direction"))){
			list.add(cb.equal(root.get("direction").as(String.class), request.getParameter("direction"))) ;
			map.put("direction", request.getParameter("direction")) ;
		}
		
		if(!StringUtils.isBlank(request.getParameter("organ"))){
			list.add(cb.equal(root.get("organ").as(String.class), request.getParameter("organ"))) ;
			map.put("organ", request.getParameter("organ")) ;
		}
		try {
			if(!StringUtils.isBlank(request.getParameter("begin")) && request.getParameter("begin").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.greaterThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("begin")))) ;
				map.put("begin", request.getParameter("begin")) ;
			}
			if(!StringUtils.isBlank(request.getParameter("end")) && request.getParameter("end").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.lessThan(root.get("createtime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("end")))) ;
				map.put("end", request.getParameter("end")) ;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		//振铃时长
		if(!StringUtils.isBlank(request.getParameter("ringdurbegin"))){
			list.add(cb.greaterThan(root.get("ringduration").as(int.class), Integer.parseInt(request.getParameter("ringdurbegin"))*1000)) ;
			map.put("ringdurbegin", request.getParameter("ringdurbegin")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("ringdurend"))){
			list.add(cb.lessThan(root.get("ringduration").as(int.class), Integer.parseInt(request.getParameter("ringdurend"))*1000)) ;
			map.put("ringdurend", request.getParameter("ringdurend")) ;
		}
		
		//通话时长
		if(!StringUtils.isBlank(request.getParameter("incallbegin"))){
			list.add(cb.greaterThan(root.get("duration").as(int.class), Integer.parseInt(request.getParameter("incallbegin"))*1000)) ;
			map.put("incallbegin", request.getParameter("incallbegin")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("incallend"))){
			list.add(cb.lessThan(root.get("duration").as(int.class), Integer.parseInt(request.getParameter("incallend"))*1000)) ;
			map.put("incallend", request.getParameter("incallend")) ;
		}
		
		//录音时长
		if(!StringUtils.isBlank(request.getParameter("recordbegin"))){
			list.add(cb.greaterThan(root.get("recordtime").as(int.class), Integer.parseInt(request.getParameter("recordbegin"))*1000)) ;
			map.put("recordbegin", request.getParameter("recordbegin")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("recordend"))){
			list.add(cb.lessThan(root.get("recordtime").as(int.class), Integer.parseInt(request.getParameter("recordend"))*1000)) ;
			map.put("recordend", request.getParameter("recordend")) ;
		}
		
		//是否漏话
		if(!StringUtils.isBlank(request.getParameter("misscall"))){
			list.add(cb.equal(root.get("misscall").as(boolean.class), Boolean.valueOf(request.getParameter("misscall")))) ;
			map.put("misscall", request.getParameter("misscall")) ;
		}
		
		//呼叫方向
		if(!StringUtils.isBlank(request.getParameter("calltype"))){
			list.add(cb.equal(root.get("calltype").as(String.class), request.getParameter("calltype"))) ;
			map.put("calltype", request.getParameter("calltype")) ;
		}
		//队列，技能组
		if(!StringUtils.isBlank(request.getParameter("quene"))){
			list.add(cb.equal(root.get("quene").as(String.class), request.getParameter("quene"))) ;
			map.put("quene", request.getParameter("quene")) ;
		}
		
		//满意度评价
		if(!StringUtils.isBlank(request.getParameter("satisfaction"))){
			if("not".equals(request.getParameter("satisfaction"))){
				list.add(cb.isNull(root.get("satisfaction").as(String.class))) ;
			}else{
				list.add(cb.equal(root.get("satisfaction").as(String.class), request.getParameter("satisfaction"))) ;
			}
			map.addAttribute("satisfaction", request.getParameter("satisfaction"));
		}
		
		//质检分数
		if(!StringUtils.isBlank(request.getParameter("qualityscorebegin"))){
			list.add(cb.greaterThanOrEqualTo(root.get("qualityscore").as(int.class), Integer.parseInt(request.getParameter("qualityscorebegin")))) ;
			map.put("qualityscorebegin", request.getParameter("qualityscorebegin")) ;
		}
		if(!StringUtils.isBlank(request.getParameter("qualityscoreend"))){
			list.add(cb.lessThanOrEqualTo(root.get("qualityscore").as(int.class), Integer.parseInt(request.getParameter("qualityscoreend")))) ;
			map.put("qualityscoreend", request.getParameter("qualityscoreend")) ;
		}
		
		if(!StringUtils.isBlank(request.getParameter("qualitypass"))) {
			boolean auto = ((request.getParameter("qualitypass")).equals("1")|| request.getParameter("qualitypass").equals("true"))?true:false;
			list.add( cb.equal(root.get("qualitypass").as(boolean.class), auto)) ;
			map.put("qualitypass", request.getParameter("qualitypass")) ;
		}
		
		//质检时间
		try {
			if(!StringUtils.isBlank(request.getParameter("qualitydistimebegin")) && request.getParameter("qualitydistimebegin").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.greaterThanOrEqualTo(root.get("qualitydistime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("qualitydistimebegin")))) ;
				map.put("qualitydistimebegin", request.getParameter("qualitydistimebegin")) ;
			}
			if(!StringUtils.isBlank(request.getParameter("qualitydistimeend")) && request.getParameter("qualitydistimeend").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.lessThanOrEqualTo(root.get("qualitydistime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("qualitydistimeend")))) ;
				map.put("qualitydistimeend", request.getParameter("qualitydistimeend")) ;
			}
			if(!StringUtils.isBlank(request.getParameter("qualitytimebegin")) && request.getParameter("qualitytimebegin").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.greaterThanOrEqualTo(root.get("qualitytime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("qualitytimebegin")))) ;
				map.put("qualitytimebegin", request.getParameter("qualitytimebegin")) ;
			}
			if(!StringUtils.isBlank(request.getParameter("qualitytimeend")) && request.getParameter("qualitytimeend").matches("[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}")){
				list.add(cb.lessThanOrEqualTo(root.get("qualitytime").as(Date.class), UKTools.dateFormate.parse(request.getParameter("qualitytimeend")))) ;
				map.put("qualitytimeend", request.getParameter("qualitytimeend")) ;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		if(!StringUtils.isBlank(request.getParameter("uuid"))){
			list.add(cb.equal(root.get("id").as(String.class), request.getParameter("uuid"))) ;
			map.put("uuid", request.getParameter("uuid")) ;
		}
		
		return list ;
	}
	
	/**
	 * 质检结果导出
	 * @param table
	 * @param statusEventList
	 * @param response
	 * @param orgi
	 * @return
	 * @throws IOException
	 */
	public static ExcelExporterQualityResultProcess Excelprocess(MetadataTable table,Page<StatusEvent> statusEventList,HttpServletResponse response,String orgi) throws IOException {
		QualityResultRepository qualityResultRes = UKDataContext.getContext().getBean(QualityResultRepository.class);
		QualityResultItemRepository qualityResultItemRes = UKDataContext.getContext().getBean(QualityResultItemRepository.class);
    	ExcelExporterQualityResultProcess excelProces = null;
    	List<TableProperties> tableproperty = new ArrayList<>();
		//自定义导出显示的字段
		if (table !=null && table.getTableproperty() != null) {
			for(TableProperties tpr :table.getTableproperty()){
				String field = tpr.getFieldname().toLowerCase();
				if (field.equals("qualitytime")) {
					tpr.setSortindex(1);
					tableproperty.add(tpr);
				}
				if (field.equals("qualityuser")) {
					tpr.setSortindex(2);
					tableproperty.add(tpr);
				}
				if (field.equals("userid")) {
					tpr.setSortindex(3);
					tableproperty.add(tpr);
				}
				if (field.equals("discaller")) {
					tpr.setSortindex(4);
					tableproperty.add(tpr);
				}
				if (field.equals("discalled")) {
					tpr.setSortindex(5);
					tableproperty.add(tpr);
				}
				if (field.equals("starttime")) {
					tpr.setSortindex(6);
					tableproperty.add(tpr);
				}
				if (field.equals("duration")) {
					tpr.setSortindex(7);
					tableproperty.add(tpr);
				}
				if (field.equals("id")) {
					tpr.setSortindex(8);
					tableproperty.add(tpr);
				}
			}
		}
		//字段排序
		Collections.sort(tableproperty, new Comparator<TableProperties>() {  
            @Override  
            public int compare(TableProperties o1, TableProperties o2) {  
                if (o1.getSortindex() > o2.getSortindex()) {  
                    return 1;  
                }  
                if (o1.getSortindex() == o2.getSortindex()) {  
                    return 0;  
                }  
                return -1;  
            }  
        });
		table.setTableproperty(tableproperty);
		Map<String, List<Map<String,Object>>> tpMap = new HashMap<String, List<Map<String,Object>>>();//模板-数据，一个模板id对应一组数据表
		Map<String, List<QualityResultExporter>> showitemMap = new HashMap<String, List<QualityResultExporter>>();//模板-质检项，一个模板id对应一组显示质检项（表头）
		Map<String, List<QualityResultItem>> tabooMap = new HashMap<String, List<QualityResultItem>>();///模板-禁忌项，一个模板id对应一组显示禁忌项（表头）
		Map<String, Integer> rowheadNumMap = new HashMap<String, Integer>();//模板-表头行数，一个模板id对应一个表头行数
		//根据模板id区分数据记录质检模板不一样的情况
		for(StatusEvent event : statusEventList){
			int rowheadNum = 1;
			List<QualityResultExporter> showitemList = new ArrayList<>();
			List<QualityResultItem> tabooList = new ArrayList<>();
			if (StringUtils.isBlank(event.getTemplateid()) || event.getQualitytime()==null) {
				event.setTemplateid("noTemplateid");
			}
			if (!StringUtils.isBlank(event.getTemplateid())) {
    			Map<String, Object> eventMap = UKTools.transBean2Map(event);
    			List<QualityResult> qcressultList =qualityResultRes.findByDataidAndOrgi(event.getId(), orgi);
    			if (qcressultList != null && qcressultList.size() > 0 ) {
    				eventMap.put("qcResult_score", qcressultList.get(0).getScore());
    				eventMap.put("qcResult_remarks", qcressultList.get(0).getRemarks());
    				eventMap.put("qcResult_adcom", qcressultList.get(0).getAdcom());
    				eventMap.put("qcResult_qacom", qcressultList.get(0).getQacom());
    				eventMap.put("qcResult_imcom", qcressultList.get(0).getImcom());
    				if (event.getQualitypass()==2) {
    					eventMap.put("qcResult_pass", "未质检");
					}else if(event.getQualitypass()==1){
						eventMap.put("qcResult_pass", "合格");
					}else if(event.getQualitypass()==0){
						eventMap.put("qcResult_pass", "不合格");
					}
    				
    				/**
    				 * 整理出需要显示的质检项（一级-二级-三级）
    				 */
					for(QualityResult rid : qcressultList){
						List<QualityResultItem> qcressultitemList = qualityResultItemRes.findByResultidAndOrgi(rid.getId(), orgi);
						if (qcressultitemList != null && qcressultitemList.size() >0) {
							for(QualityResultItem item1 : qcressultitemList){
								if (!StringUtils.isBlank(item1.getType()) && item1.getType().equals(UKDataContext.QcTemplateItemType.TABOO.toString())) {
									rowheadNum = rowheadNum<=2?2:rowheadNum;
									tabooList.add(item1);
									eventMap.put(item1.getItemid(), item1.getScore()==0?"否":"是");
								}else if (StringUtils.isBlank(item1.getParentid()) || item1.getParentid().equals("0")) {
									int col1 = 0;
									QualityResultExporter exporter1 = new QualityResultExporter();
									exporter1.setChildren(new ArrayList<QualityResultExporter>());
									for(QualityResultItem item2 : qcressultitemList){
										if (!StringUtils.isBlank(item2.getParentid()) && item2.getParentid().equals(item1.getItemid())) {
											rowheadNum = rowheadNum<=2?2:rowheadNum;
											int col2 = 0;
											QualityResultExporter exporter2 = new QualityResultExporter();
											exporter2.setChildren(new ArrayList<QualityResultExporter>());
											exporter2.setItem(item2);
											for(QualityResultItem item3 : qcressultitemList){
												if (!StringUtils.isBlank(item3.getParentid()) && item3.getParentid().equals(item2.getItemid())) {
													rowheadNum = rowheadNum<=3?3:rowheadNum;
													QualityResultExporter exporter3 = new QualityResultExporter();
													exporter3.setItem(item3);
													exporter2.getChildren().add(exporter3);
													col2++;
													eventMap.put(item3.getItemid(), item3.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?-item3.getScore():item3.getScore());
												}
											}
											exporter2.setColinx(col2==0?1:col2);
											col1 = col1+exporter2.getColinx();
											exporter1.getChildren().add(exporter2);
											if (col2==0) {
												eventMap.put(item2.getItemid(), item2.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?-item2.getScore():item2.getScore());
											}
										}
									}
									exporter1.setColinx(col1==0 ?1:col1);
									exporter1.setItem(item1);
									showitemList.add(exporter1);
									if (col1==0) {
										eventMap.put(item1.getItemid(), item1.getType().equals(UKDataContext.QcTemplateItemType.MINUS.toString())?-item1.getScore():item1.getScore());
									}
								}
							}
						}
					}
				}
    			//模板id+版本号 区分表头
    			String tpKey = event.getTemplateid()+Integer.toString(event.getTemplatever());
    			
    			List<Map<String,Object>> values = tpMap.get(tpKey);
    			if (values == null ) {
    				values = new ArrayList<Map<String,Object>>();
				}
    			values.add(eventMap);
    			
    			if (tpMap.get(tpKey)==null) {
    				tpMap.put(tpKey, values);
				}
    			if (showitemMap.get(tpKey)==null) {
    				showitemMap.put(tpKey, showitemList);
				}
    			if (rowheadNumMap.get(tpKey)==null) {
    				rowheadNumMap.put(tpKey, rowheadNum);
				}
    			if (tabooMap.get(tpKey)==null) {
    				tabooMap.put(tpKey, tabooList);
				}
			}
		}
		if (tpMap != null && tpMap.size() > 0 && showitemMap != null && showitemMap.size() > 0) {
			String sdf = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			response.setHeader("content-disposition", "attachment;filename=UCKeFu-qcResult-"+sdf+".xlsx");  
			excelProces = new ExcelExporterQualityResultProcess( tpMap,showitemMap,tabooMap,rowheadNumMap, table, response.getOutputStream()) ;
		}
		return excelProces;
	}
	
}
